package com.shixj.easy.spider.service;

import com.google.common.base.Strings;
import com.shixj.easy.spider.mapper.GuestMapper;
import com.shixj.easy.spider.model.Guest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.vankid.common.utils.weixin.WeixinHelper;
import pers.vankid.common.utils.weixin.model.WeixinSessionBody;

import java.util.Date;

@Service
public class WeixinAuthcServiceImpl implements WeixinAuthcService {
    @Autowired
    private WeixinHelper weixinHelper;
    @Autowired
    private GuestMapper guestMapper;

    @Override
    public Guest login(Guest guest) throws Exception {
        WeixinSessionBody weixinSessionBody = weixinHelper.getWxSessionBody(guest.getCode());
        if (weixinSessionBody != null && !Strings.isNullOrEmpty(weixinSessionBody.getOpenid())) {
            Guest query = new Guest();
            query.setOpenId(weixinSessionBody.getOpenid());
            Guest guest1 = guestMapper.selectOne(query);
            if (guest1 != null && guest1.getId() > 0) {
                //授权过
                guest1.setNickName(guest1.getNickName());
                guest1.setTitle(guest1.getTitle());
                guestMapper.updateByPrimaryKeySelective(guest1);
                return guest1;
            } else {
                //第一次授权登陆
                guest.setOpenId(weixinSessionBody.getOpenid());
                guest.setCreateTime(new Date());
                guestMapper.insert(guest);
                return guest;
            }
        } else throw new Exception("授权失败");
    }

}
